package com.cheyunkeji.er.fragment.auction;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.ChannelSelectActivity;
import com.cheyunkeji.er.activity.ModuleSelectActivity;
import com.cheyunkeji.er.activity.auction.AuctionRecordActivity;
import com.cheyunkeji.er.activity.auction.CooperatorListActivity;
import com.cheyunkeji.er.activity.auction.EditPersonalInfoActivity;
import com.cheyunkeji.er.activity.auction.EditingInformationActivity;
import com.cheyunkeji.er.activity.auction.HomeActivity;
import com.cheyunkeji.er.activity.fast_evaluate.CallCenterActivity;
import com.cheyunkeji.er.activity.fast_evaluate.NoticeActivity;
import com.cheyunkeji.er.app.PushMsgManager;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.UserInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.view.SToast;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Michael Chen
 */

public class MineFragment extends BaseFragment {


    @BindView(R.id.iv_photo)
    CircleImageView ivPhoto;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_tele_number)
    TextView tvTeleNumber;
    @BindView(R.id.tv_wdb_count)
    TextView tvWdbCount;
    @BindView(R.id.mine_item_debiao)
    RelativeLayout mineItemDebiao;
    @BindView(R.id.tv_liubiao_count)
    TextView tvLiubiaoCount;
    @BindView(R.id.mine_item_undebiao)
    RelativeLayout mineItemUndebiao;
    @BindView(R.id.tv_debiao_count)
    TextView tvDebiaoCount;
    @BindView(R.id.mine_item_liubiao)
    RelativeLayout mineItemLiubiao;
    @BindView(R.id.iv_partner)
    ImageView ivPartner;
    @BindView(R.id.rl_partner)
    RelativeLayout rlPartner;
    @BindView(R.id.iv_auction_record)
    ImageView ivAuctionRecord;
    @BindView(R.id.rl_auction_record)
    RelativeLayout rlAuctionRecord;
    @BindView(R.id.iv_icon2)
    ImageView ivIcon2;
    @BindView(R.id.rl_switch_shop)
    RelativeLayout rlSwitchShop;
    @BindView(R.id.iv_icon4)
    ImageView ivIcon4;
    @BindView(R.id.rl_notices)
    RelativeLayout rlNotices;
    @BindView(R.id.iv_icon5)
    ImageView ivIcon5;
    @BindView(R.id.rl_call_center)
    RelativeLayout rlCallCenter;
    @BindView(R.id.btn_logout)
    Button btnLogout;
    @BindView(R.id.iv_unread_dot)
    ImageView ivUnreadDot;
    @BindView(R.id.rl_switch_module)
    RelativeLayout rlSwitchModule;
    @BindView(R.id.ll_switch_module)
    LinearLayout llSwitchModule;
    private PushMsgManager pushMsgManager;
    @BindView(R.id.lv_switch_shop_line)
    View lvSwitchShop;
    @BindView(R.id.cheshanglayout)
    RelativeLayout cheshanglayout;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_mine_layout, container, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {

    }

    @Override
    protected void initView() {

        int head = R.drawable.er_evaluate_mine_noman;
        switch (Integer.parseInt(UserInfoManager.getInstance(MyApplication.getInstance()).getGender())) {
            case 0:
                head = R.drawable.er_evaluate_mine_noman;
                break;
            case 1:
                head = R.drawable.er_evaluate_mine_default_photo;
                break;
            case 2:
                head = R.drawable.er_evaluate_mine_woman;
                break;
            default:
                break;
        }

        UserInfo.ChannelListBean currentChannel = ChannelInfoUtil.getCurrentChannelInfo();
        int moduleCount = currentChannel.getIsarchiver() + currentChannel.getIsauction() + currentChannel.getIsrapid();

        if (moduleCount != 0 && moduleCount != 1) {
            llSwitchModule.setVisibility(View.VISIBLE);
            rlSwitchModule.setOnClickListener(this);
        }

        ivPhoto.setImageResource(head);
        ivPhoto.setOnClickListener(this);
        rlAuctionRecord.setOnClickListener(this);
        rlPartner.setOnClickListener(this);
        rlNotices.setOnClickListener(this);
        rlCallCenter.setOnClickListener(this);
        btnLogout.setOnClickListener(this);
        rlSwitchShop.setOnClickListener(this);
        cheshanglayout.setOnClickListener(this);

    }

    @Override
    protected void initData() {

        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName())) {
            tvUserName.setText(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName());
        }

        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getMobile())) {
            String mobile = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
            if(mobile.length()>=11) {
                tvTeleNumber.setText(mobile.replaceFirst(mobile.substring(3, 7), "****"));
            }
        }

        setRecordCount();
        showUnreadMsgCount();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
            return;
        } else {  // 在最前端显示 相当于调用了onResume();
            //网络数据刷新
            setRecordCount();
            showUnreadMsgCount();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName())) {
            tvUserName.setText(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName());
        }

        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getMobile())) {
            String mobile = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
            if(mobile.length()>=11) {
                tvTeleNumber.setText(mobile.replaceFirst(mobile.substring(3, 7), "****"));
            }
        }
    }


    private void showUnreadMsgCount() {

        dealWithPushMsg();
    }

    private void setRecordCount() {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

        ApiClient.postForm(HttpConstants.AUCTION_RESULT_STATISTICS, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                // 网络异常
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                try {

                    JSONObject object = new JSONObject(response);

                    if (object.optInt("code") == 1) {

                        JSONObject obj = object.getJSONObject("data");

                        if (null != obj) {
                            int winCount = obj.optInt("is_win_count");
                            int failedCount = obj.optInt("is_fail_count");
                            int unsoldCount = obj.optInt("is_unsold_count");
                            tvDebiaoCount.setText(String.valueOf(winCount));
                            tvWdbCount.setText(String.valueOf(failedCount));
                            tvLiubiaoCount.setText(String.valueOf(unsoldCount));
                        }

                    } else {
                        SToast.show("数据获取失败");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View v) {

        Intent intent;
        switch (v.getId()) {
            case R.id.iv_photo:
                startActivity(new Intent(getActivity(), EditingInformationActivity.class));
                break;
            case R.id.cheshanglayout:
                startActivity(new Intent(getActivity(), EditPersonalInfoActivity.class));
                break;
            case R.id.rl_partner:
                startActivity(new Intent(getActivity(), CooperatorListActivity.class));
                break;
            case R.id.rl_auction_record:
                startActivity(new Intent(getActivity(), AuctionRecordActivity.class));
                break;
            case R.id.rl_switch_shop:
                intent = new Intent(getActivity(), ChannelSelectActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_notices:

                intent = new Intent(getActivity(), NoticeActivity.class);
                startActivity(intent);

                if (null == pushMsgManager)
                    pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this.getActivity()).getAccount());
                pushMsgManager.clearNotifyMsgRecordCount(PushMsgManager.MSG_TYPE_ZHANNEIXIN);

                break;

            case R.id.rl_call_center:
                startActivity(new Intent(getActivity(), CallCenterActivity.class));
                break;

            case R.id.btn_logout:
//                MyApplication.phone = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
//                MyApplication.pwd = UserInfoManager.getInstance(MyApplication.getInstance()).getPwd();
                UserInfoManager.getInstance(MyApplication.getInstance()).clear();
//                MyApplication.logout(MyApplication.getInstance());
                break;

            case R.id.rl_switch_module:

                startActivity(new Intent(this.getActivity(), ModuleSelectActivity.class));
                break;

            default:
                break;
        }

    }


    /**
     * 显示是否有未读消息
     */
    public void dealWithPushMsg() {

        if (null == pushMsgManager)
            pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this.getActivity()).getAccount());

        int msgCount = pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_ZHANNEIXIN);
        if (msgCount == 0) {
            ivUnreadDot.setVisibility(View.GONE);
        } else {
            ivUnreadDot.setVisibility(View.VISIBLE);
        }
        ((HomeActivity) getActivity()).refreshBottomMsgCount();

    }
}
